package com.yygo.webapp.controller.material;

import com.yygo.model.LoanRequest;
import com.yygo.model.Material;
import com.yygo.model.MaterialAudit;
import com.yygo.service.LoanRequestManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tiansha on 2015/11/6.
 */
public class BaseMaterialController {

    @Autowired
    protected LoanRequestManager loanRequestManager;

    protected List<Material> buildCompleteMaterials(MaterialAudit materialAudit) {
        LoanRequest loanRequest = loanRequestManager.getLoanRequest(materialAudit.getLoanRequest().getId());
        List<String> completeMaterials = loanRequest.getLoanProduct().getCompleteLoanMaterialNames();
        List<String> loanMaterials = loanRequest.getLoanProduct().getLoanMaterialNames();
        List<Material> materials = new ArrayList<>();
        for (String name : completeMaterials) {
            Material material = new Material();
            material.setName(name);
            materials.add(material);
            material.setIsLoanRequest(isLoanRequest(loanMaterials, name));
        }
        return materials;
    }

    private boolean isLoanRequest(List<String> loanMaterials, String name) {
        for (String str : loanMaterials) {
            if (str.equals(name)) return true;
        }
        return false;
    }

    protected void mergeMaterials(List<Material> materials, List<Material> completeMaterials) {
        for (Material material : completeMaterials) {
            for (Material item : materials) {
                if (material.equals(item)) {
                    material.setId(item.getId());
                    material.setReceived(item.isReceived());
                    material.setSent(item.isSent());
                    material.setReceiveDate(item.getReceiveDate());
                    material.setSendDate(item.getSendDate());
                    material.setShipNumber(item.getShipNumber());
                    material.setReceiveOperator(item.getReceiveOperator());
                }
            }
        }
    }

    protected Material getMaterial(MaterialAudit materialAudit, String name) {
        for (Material material : materialAudit.getMaterialList()) {
            if (material.getName().equals(name))
                return material;
        }
        return null;
    }
}
